package com.atguigu.cloud.mygateway;

import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {
	public MyRoutePredicateFactory() {
		super(MyRoutePredicateFactory.Config.class);
	}
	
	@Override
	public List<String> shortcutFieldOrder() {
		return Collections.singletonList("userType");
	}
	
	@Override
	public Predicate<ServerWebExchange> apply(Config config) {
		return new GatewayPredicate() {
			public boolean test(ServerWebExchange exchange) {
				List<String> userType = exchange.getRequest().getQueryParams().get("userType");
				if (userType == null) return false;
				
				//如果说参数存在，就和config的数据进行比较
				return userType.equals(config.getUserType());
			}
		};
	}
	
	@Validated
	public static class Config {
		@Setter
		@Getter
		@NotEmpty
		private String userType; //钻、金、银等用户等级
		
	}
}